﻿var virualpath = "../../"
var prourlid = 0;
var AdminName = "";
var Password = "";
var instance = "";
$(function () {
    var res = window.location.search;
    var resdata = res.split(",")
    if (res == "") {
        location.href = "index.html"
    } else {
        if (resdata.length <= 1) {
            prourlid = resdata[0].split("=")[1];
        } else {
            prourlid = resdata[0].split("=")[1];
            AdminName = resdata[1].split("=")[1];
            Password = resdata[2].split("Pwd=")[1];
            sessionStorage.setItem("Proid", "" + prourlid + "")
        }
        var second = 0;
        window.setInterval(function () {
            second++;
        }, 1000);
        var tjArr = localStorage.getItem("jsArr") ? localStorage.getItem("jsArr") : '[{}]';
        $.cookie('tjRefer', getReferrer(), { expires: 1, path: '/' });
        window.onbeforeunload = function () {
            if ($.cookie('tjRefer') == '') {
                var tjT = eval('(' + localStorage.getItem("jsArr") + ')');
                if (tjT) {
                    tjT[tjT.length - 1].time += second;
                    var jsArr = JSON.stringify(tjT);
                    localStorage.setItem("jsArr", jsArr);
                }
            } else {

                var tjArr = localStorage.getItem("jsArr") ? localStorage.getItem("jsArr") : '[{}]';
                var dataArr = {
                    'CoreseId': prourlid,
                    'AdminId': sessionStorage.getItem("AdminId"),
                    'url': location.href,
                    'time': second,
                    'refer': getReferrer(),
                    'timeIn': new Date(+new Date() + 8 * 3600 * 1000 - (second * 1000)).toJSON().substr(0, 19).replace("T", " "),
                    'timeOut': new Date(+new Date() + 8 * 3600 * 1000).toJSON().substr(0, 19).replace("T", " "),
                };
                tjArr = eval('(' + tjArr + ')');
                tjArr.push(dataArr);
                tjArr = JSON.stringify(tjArr);
                localStorage.setItem("jsArr", tjArr);

            }
            var list = JSON.parse(localStorage.getItem("jsArr"));
            console.log(list)
            var obj = {};
            obj.AdminId = list[list.length - 1].AdminId;
            obj.ResourceId = list[list.length - 1].CoreseId;
            obj.StartTime = list[list.length - 1].timeIn;
            obj.EndTime = list[list.length - 1].timeOut;
            $.ajax({
                url: virualpath + '/Project/InsertProBrowseInfo',
                type: 'post',
                data: JSON.stringify(obj),
                async: true,
                dataType: 'json',
                contentType: 'application/json',
                success: function (data) {
                }
            })
        };
        function getReferrer() {
            var referrer = '';
            try {
                referrer = window.top.document.referrer;
            } catch (e) {
                if (window.parent) {
                    try {
                        referrer = window.parent.document.referrer;
                    } catch (e2) {
                        referrer = '';
                    }
                }
            }
            if (referrer === '') {
                referrer = document.referrer;
            }
            console.log(referrer);
        }

    }
    $.ajax({
        url: virualpath + '/Session/GetSessionAsync',
        type: 'get',
        async: true,
        contentType: 'application/json',
        success: function (data) {
            var res = JSON.parse(data);
            if (res != undefined) {
                GetProinfo(prourlid);
            } else {
                if (AdminName != "" && Password != "") {
                    var field = {};
                    field.AdminName = AdminName;
                    field.EncryptPwd = Password;
                    $.ajax({
                        url: virualpath + '/Login/LocationSignIn',
                        type: 'post',
                        dataType: 'json',
                        data: JSON.stringify(field),
                        contentType: 'application/json',
                        async: true,
                        success: function (data) {
                            if (data.RspCode == 1) {
                                GetCourseinfo(prourlid);
                            }
                            if (data.RspCode == 0) {
                                location.href = "index.html"
                            }

                        }
                    })
                } else {
                    alert("请先登录")
                    location.href = "login.html";
                }
            }
        }
    })

})

function playPause(id) {
    if (id == 0) {
        var myVideo = document.getElementsByTagName('video')[id];
        if (myVideo.paused) {
            myVideo.play();
            $('#playTip').removeClass('playTip').addClass('playTip2').fadeOut();
        }
        else {
            myVideo.pause();
            $('#playTip').removeClass('playTip2').addClass('playTip').fadeIn();
        }
    }
    else {
        var myVideo = document.getElementsByTagName('video')[id];
        if (myVideo.paused) {
            myVideo.play();
            $('#playTip_p').removeClass('playTip_p').addClass('playTip2_p').fadeOut();
        }
        else {
            myVideo.pause();
            $('#playTip_p').removeClass('playTip2_p').addClass('playTip_p').fadeIn();
        }
    }
}

window.document.oncontextmenu = function () {
    //alert('请不要点击鼠标右键！');
    return false;
}



// 点击按钮获取分数
function InsertFee() {
    if ($("#projectNamddl").val() == '') {
        alert("请给课程评分！");
        return;
    }
    if ($("#FeeName").val() == '') {
        alert("请输入反馈！");
        return;
    }
    var obj = {};
    obj.Fee_Content = $("#FeeName").val();
    obj.ProId = prourlid;
    obj.AdminId = sessionStorage.getItem("AdminId")
    //obj.Grade = instance.config.value;
    obj.Grade = $("#projectNamddl").val();
    $.ajax({
        url: virualpath + '/Feedback/InsertFeedback',
        type: 'Post',
        data: JSON.stringify(obj),
        async: true,
        dataType: 'json',
        contentType: 'application/json',
        success: function (d) {
            if (d > 0) {
                alert('提交成功')
                location.reload();
            } else if (d < 0) {
                alert('本课程该学员已反馈！')
            } else if (d== 0) {
                alert('提交失败');
            }
        }
    })
}
function GetProinfo(id) {
    var obj = {};
    obj.id = id;
    $.ajax({
        url: virualpath + '/Project/GetByIdProjectInfo',
        type: 'get',
        data: obj,
        async: true,
        dataType: 'json',
        contentType: 'application/json',
        success: function (data) {
            var resultData = data
            if (resultData != undefined) {
                var TopLeftsidestr = "";
               // TopLeftsidestr += '<div class="video"><video id="playVideo" onclick="playPause(0)" width="618" height="348" poster="' + resultData.Pro_Filepath + resultData.Pro_VideoImg + '"><source src="' + resultData.Pro_Filepath + resultData.Pro_VideoUrl + '" type="video/mp4" /><p>您的浏览器版本过低，请使用IE9.0或更高版本的浏览器。</p></video><div id="playTip" class="playTip" onclick="playPause(0)"></div></div><div class="btnvideo"><a href="#" class="cgal" onClick="show()"><img src="images/open.png" width="18px;"></a></div><div class="mask" style="display: none;" id="mask"></div><div id="pop_div" class="pop_box"><div class="p_head"><div class="p_h_title"><video id="playVideo" onclick="playPause(1)" width="1160" height="653" poster="' + resultData.Pro_VideoImg + '"><source src="' + resultData.Pro_Filepath + resultData.Pro_VideoUrl + '" type="video/mp4" /><p>您的浏览器版本过低，请使用IE9.0或更高版本的浏览器。</p></video></div><div><a class="p_h_x" onclick="hideDiv(pop_div);" title="关闭窗口"></a></div><div id="playTip_p" class="playTip_p" onclick="playPause(1)"></div></div></div>';
                TopLeftsidestr += '<div class="video"><video poster="' + resultData.Pro_Filepath + resultData.Pro_VideoImg + '" width="618" height="348" controls><source src="' + resultData.Pro_Filepath + resultData.Pro_VideoUrl + '" type="video/mp4"></video></div></div></div>';

                $(".toppart .leftside").append(TopLeftsidestr);

                var TopRightsidestr = "";
                TopRightsidestr += '<div class="teacher">' + resultData.Company + resultData.Position + '&nbsp;' + resultData.Section + '</div><div class="title">' + resultData.Pro_Name + '&nbsp;&nbsp;课程介绍</div><div class="info">' + resultData.Pro_Description + '</div>';
                $(".toppart .rightside").append(TopRightsidestr);

                var Pro_Coursestr = "";
                Pro_Coursestr += '' + resultData.Pro_Description + '<br/><br/><br/>' + resultData.Pro_Course + '';
                $("#Pro_Course").append(Pro_Coursestr);

                var menustr = "";
                menustr += ' <ul class="navi"><li class="one"><a href="Project.html?id=1">' + resultData.Pro_Name + '</a></li></ul>';
                $("#menu").append(menustr)
                sessionStorage.setItem("ProName", "" + resultData.Pro_Name + "")

                GetTeach(resultData.Pro_TeachId)
                GetTextBooks(resultData.Pro_Textbooks)
                GetBooks(resultData.Pro_Books)
                GetWebsites(resultData.Pro_Websites)
                GetFeedback(resultData.Id)

                GetCourse(resultData.Id)
                layui.use(['form', 'layedit', 'laydate', 'layer'], function () {
                    var layedit = layui.layedit
                    var form = layui.form
                    var layer = layui.layer
                    var Syllabus = layedit.build('Syllabus', {
                        height: 280, //设置编辑器高度
                        tool: [
                            'strong' //加粗
                            , 'italic' //斜体
                            , 'underline' //下划线
                            , 'del' //删除线
                            , '|' //分割线
                            , 'left' //左对齐
                            , 'center' //居中对齐
                            , 'right' //右对齐
                            , 'help' //帮助
                        ]
                    });
                    layedit.setContent(Syllabus, resultData.Pro_Syllabus);
                });


            }
        }
    })
}

function GetTeach(id) {
    $("#Teachlist").empty();
    $.ajax({
        url: virualpath + '/Project/GetTeachAsync',
        type: 'get',
        data: { "id": "" + id + "" },
        async: true,
        dataType: 'json',
        contentType: 'application/json',
        success: function (data) {
            var resultData = data;
            if (resultData != undefined) {
                var str = "";
                for (var i = 0; i < Object.keys(resultData).length; i++) {
                    str += ' <div class="namecard"> <div class="face"><img src="' + resultData[i].Filepath + resultData[i].Photo + '" width="110" height="110" /></div><div class="name"><p class="top">' + resultData[i].TName + '</p><p class="btm">' + resultData[i].Company + '<br />' + resultData[i].Position + '<br/>' + resultData[i].Section + '</p></div></div>'
                }
                $("#Teachlist").append(str);
            }
        }
    })

}

//获取材料列表
function GetTextBooks(id) {
    //var obj = {};
    //obj.id =  id;
    $.ajax({
        url: virualpath + '/Textbook/GetByIdTextbookInfo',
        type: 'get',
        data: { "id": "" + id + "" },
        async: true,
        dataType: 'json',
        contentType: 'application/json',
        success: function (data) {
            var resultData = data;
            if (resultData != undefined) {
                var Pro_Textbooksstr = "";
                for (var i = 0; i < Object.keys(resultData).length; i++) {
                    Pro_Textbooksstr += ' <div class="onelist"><div class="pic" > <img src="' + resultData[i].Filepath + resultData[i].Img + '" width="244" height="335" alt="" /></div ><div class="tit"><span class="font14 bold fray">' + resultData[i].TextName + '</span><br>' + resultData[i].TextAuthor + '<br>' + resultData[i].Publishing + '</div></div>'
                }
                $("#Pro_Textbooks").append(Pro_Textbooksstr);
            }
        }
    })
}

//获取书目列表
function GetBooks(id) {
    $.ajax({
        url: virualpath + '/Book/GetByIdBookInfo',
        type: 'get',
        data: { "id": "" + id + "" },
        async: true,
        dataType: 'json',
        contentType: 'application/json',
        success: function (data) {
            var resultData = data
            if (resultData != undefined) {
                var Pro_Booksstr = "";
                for (var i = 0; i < Object.keys(resultData).length; i++) {
                    Pro_Booksstr += '<div class="onelist"><div class="pic" > <img src="' + resultData[i].Filepath + resultData[i].Img + '" width="244" height="335" alt="" /></div ><div class="tit"><span class="font14 bold fray">' + resultData[i].BookName + '</span><br>' + resultData[i].BookAuthor + '<br>' + resultData[i].Publishing + '</div></div>'
                }

                $("#Pro_Books").append(Pro_Booksstr);
            }
        }
    })
}

//获取参考网站列表
function GetWebsites(id) {
    $.ajax({
        url: virualpath + '/Website/GetByIdWebsiteInfo',
        type: 'get',
        data: { "id": "" + id + "" },
        async: true,
        dataType: 'json',
        contentType: 'application/json',
        success: function (data) {
            var resultData = data
            if (resultData != undefined) {
                var Pro_Websitesstr = "";
                for (var i = 0; i < Object.keys(resultData).length; i++) {
                    Pro_Websitesstr += ' <div class="onelist"><div class="pic" > <img src="' + resultData[i].Filepath + resultData[i].Img + '" width="244" height="335" alt="" /></div ><div class="tit"><a href="' + resultData[i].WebUrl + '" target="_blank">' + resultData[i].WebUrl + '</a></div></div >'
                }
                $("#Pro_Websites").append(Pro_Websitesstr);
            }
        }
    })
}
var fabk;
var aaa = 0;
//显示反馈全部内容；
function GetFeedbackList() {
    $("#Feedback").empty();
    var str = "";

    for (var i = 0; i < fabk.length; i++) {
        str += ' <div class="onelist"><div class="info"><span class="name">' + fabk[i].LinkName + ' 同学的反馈</span><span class="time">（' + fabk[i].CreateTime + '）</span><div style="float:right" id="FeeGrade' + fabk[i].Id + '"></div></div><div class="cont">评分:' + fabk[i].Grade + " , " + fabk[i].Fee_Content + '</div><a class="btn_blu_m2"  onclick="DeleteFeedback(' + fabk[i].Id + ',' + fabk[i].AdminId + ')" >删除</a></div >'
    }
    $("#Feedback").append(str);
}



//获取反馈列表
function GetFeedback(id) {
    var obj = {};
    obj.id = id;
    $.ajax({
        url: virualpath + '/Feedback/GetByIdFeeInfo',
        type: 'get',
        data: { "id": "" + id + "" },
        async: true,
        dataType: 'json',
        contentType: 'application/json',
        success: function (data) {
            var resultData = data
            if (resultData != undefined) {
                fabk = resultData;
                var str = "";
                for (var i = 0; i < Object.keys(resultData).length; i++) {
                    str += ' <div class="onelist"><div class="info"><span class="name">' + resultData[i].LinkName + ' 同学的反馈</span><span class="time">（' + resultData[i].CreateTime + '）</span><div style="float:right" id="FeeGrade' + resultData[i].Id + '"></div></div><div class="cont">评分:' + resultData[i].Grade + " , " + resultData[i].Fee_Content + '</div><a class="btn_blu_m2"  onclick="DeleteFeedback(' + resultData[i].Id + ',' + resultData[i].AdminId + ')" >删除</a></div >'
                    if (i >= 4) {
                        aaa = 1;
                        break;
                    }
                }
                $("#Feedback").append(str);
            }
            //layui.use(['rate'], function () {
            //    var avgGrade = 0;
            //    var rate = layui.rate;
            //    for (var i = 0; i < Object.keys(resultData).length; i++) {
            //        rate.render({
            //            elem: '#FeeGrade' + resultData[i].Id + '',
            //            length: 5,
            //            value: resultData[i].Grade,
            //            readonly: true
            //        });
            //        avgGrade += resultData[i].Grade
            //    }
            //    var avg = (avgGrade / Object.keys(resultData).length);
            //    //基础效果
            //    rate.render({
            //        elem: '#feesumGrade',
            //        value:avg ,
            //        readonly: true
            //    })

            //     instance = rate.render({
            //        elem: '#test1',
            //        length: 5,
            //     });
            //    $("#GradeContent").text("总 " + Object.keys(resultData).length + " 条反馈   " + avg + "/5")
            //})

            var avgGrade = 0;
            for (var i = 0; i < Object.keys(resultData).length; i++) {

                avgGrade += resultData[i].Grade
            }
            var avg = 0;
            if (Object.keys(resultData).length >0) {
                avg = (avgGrade / Object.keys(resultData).length);
                avg = parseInt(avg);
            }
          

            $("#GradeContent").text("本课程一共" + Object.keys(resultData).length + " 条反馈 ,平均评分:" + avg);


            if (aaa == 1) {

                $("#fkxs").show();
            } else {

                $("#fkxs").hide();
            }
        }
    })
}

//保留一位小数；
//function returnFloat1(value) {
//    value = Math.round(parseFloat(value) * 10) / 10;
//    if (value.toString().indexOf(".") < 0) {
//        value = value.toString() + ".0";
//    }
//    return value;
//}
//删除课程反馈
function DeleteFeedback(id, aid) {
    var obj = {};
    obj.id = id;
    if (sessionStorage.getItem("AdminId") == aid || sessionStorage.getItem("AdminId") == 1) {
        if (confirm("确定删除吗")) {
            $.ajax({
                url: virualpath + 'Feedback/DeleteFeedback',
                type: 'post',
                data: JSON.stringify(obj),
                async: true,
                dataType: 'json',
                contentType: 'application/json',
                success: function (data) {
                    if (data > 0) {
                        alert("删除成功")
                        location.reload();
                    } else {
                        alert('删除失败')
                    }
                }
            })
        }
    } else {
        alert("不可删除他人反馈内容！")
    }
}

//获取课程列表
function GetCourse(ProId) {
    var obj = {};
    obj.ProId = ProId;
    $.ajax({
        url: virualpath + '/Course/GetByProIdCourseList',
        type: 'Get',
        data: obj,
        async: true,
        dataType: 'json',
        contentType: 'application/json',
        success: function (data) {
            var resultData = data
            if (resultData != undefined) {
                var str = "";
                for (var i = 0; i < Object.keys(resultData).length; i++) {
                    if (i > 5) {
                        str += '<div id="hidder" name="hidder" class="onelist" onclick="Location(' + resultData[i].Id + ',' + ProId + ')" style="cursor:pointer;display:none"><div class="cont" ><div class="pic"><img src="' + resultData[i].Course_Filepath + resultData[i].Course_BackImg + '" width="290" height="163" /></div><div class="info"><p class="time"><b></b><span>' + resultData[i].Course_Videomin + '</span></p><p class="recom"><b></b><span>' + resultData[i].Course_LikeNumber + '个喜欢</span></p><p class="browse"><b></b><span>' + resultData[i].Course_BrowseNumber + '人次浏览</span></p><p class="comm"><b></b><span>' + resultData[i].Course_CommentNumber + '人评论</span></p></div></div ><div class="title">' + resultData[i].Course_Name + '</div></div >'
                    } else {
                        str += '<div class="onelist" onclick="Location(' + resultData[i].Id + ',' + ProId + ')" style="cursor:pointer;"><div class="cont" ><div class="pic"><img src="' + resultData[i].Course_Filepath + resultData[i].Course_BackImg + '" width="290" height="163" /></div><div class="info"><p class="time"><b></b><span>' + resultData[i].Course_Videomin + '</span></p><p class="recom"><b></b><span>' + resultData[i].Course_LikeNumber + '个喜欢</span></p><p class="browse"><b></b><span>' + resultData[i].Course_BrowseNumber + '人次浏览</span></p><p class="comm"><b></b><span>' + resultData[i].Course_CommentNumber + '人评论</span></p></div></div ><div class="title">' + resultData[i].Course_Name + '</div></div >'
                    }
                }
                if (Object.keys(resultData).length > 5) {
                    str += "<div id='more' class='btn_box'><a onclick='Show()'>浏览更多知识点</a></div>"
                }
                if (ProId == 13) {
                    str += '<div class="tile" onclick="GZH()"><div class="text"><h1>交医检验系输血频道</h1><h2 class="">扫码关注 微信公众号</h2><p class="animate-text">上海交通大学医学院检验系输血教研室<br>与你一起走进输血学的世界!</p><div class="dots"><span></span><span></span><span></span></div></div><div class="img"><img src="images/wechat.jpg"></div></div>';
                }
                if (ProId == 1) {
                    str += '<div class="tile" onclick="GZH()"><div class="text"><h1>临床血液学教研室</h1><h2 class="">扫码关注 微信公众号</h2>  <p class="animate-text">上海交通大学医学院检验系临床血液学教研室<br>我们在这里等你！</p><div class="dots"><span></span><span></span><span></span></div></div><div class="img"><img src="images/wechat2.jpg"></div></div>';
                }

                $("#courseitem").append(str);
                //var actionbtn = '<div class="btnbox"><a href="Course.html?/id=' + resultData[0].Id + ',Proid=' + ProId+'">马上开始学习</a></div>';
                //$(".toppart .rightside").append(actionbtn);
            }
        }
    })
}

function Show() {
    $('.onelist').css('display', '')
    $('#more').css('display', 'none')
}



function Location(id, pid) {
    location.href = "Course.html?id=" + id + ",Proid=" + pid + "";
}

function GZH() {
    location.href = "wechat.html";
}


$().ready(function () {
});

function show() {
    popupDiv();
}
function popupDiv() {
    var myVideo = document.getElementsByTagName('video')[0];
    myVideo.pause();
    $('#playTip').removeClass('playTip2').addClass('playTip').fadeIn();

    var div_obj = $("#pop_div");
    //窗口宽度,高度
    var winWidth = $(window).width();
    var winHeight = $(window).height();
    //弹出的div的宽度,高度
    var popHeight = div_obj.height();
    var popWidth = div_obj.width();
    div_obj.animate({ opacity: "show", left: (winWidth - popWidth) / 2, top: (winHeight - popHeight) / 2, width: popWidth, height: popHeight }, 300);
    $("#mask").show();
}
function hideDiv() {

    var myVideo = document.getElementsByTagName('video')[1];
    myVideo.pause();
    $('#playTip2_p').removeClass('playTip2_p').addClass('playTip_p').fadeIn();


    $("#pop_div").animate({ opacity: "hide" }, 300);
    $("#mask").hide();
}